package syscore_service

import (
	"errors"

	"github.com/EDDYCJY/go-gin-example/models"
	"github.com/EDDYCJY/go-gin-example/pkg/util"
)

type GetInstitution struct {
	InstitutionID int
	PageNum       int
	PageSize      int
}

func (t *GetInstitution) GetInstitution() (interface{}, error) {
	maps := map[string]interface{}{}
	total, _ := models.GetInstitutionTotal(maps)
	goodsList, _ := models.GetInstitutionPage([]string{"institution_id", "institution_name"}, maps, t.PageNum, t.PageSize, "")
	var lists []interface{}
	for _, v := range goodsList {
		params := map[string]interface{}{
			"institution_id":   v.InstitutionID,
			"institution_name": v.InstitutionName,
		}
		lists = append(lists, params)
	}
	return map[string]interface{}{
		"lists": lists,
		"total": total,
	}, nil
}

// Login 定义登录请求结构体
type AddInstitution struct {
	InstitutionID   int
	InstitutionName string
	Contact         string
	UserName        string
	UserPassword    string
}

// AddInstitution 执行用户登录逻辑
func (t *AddInstitution) AddInstitution() (map[string]interface{}, error) {
	// 检查机构是否已存在（事务外）
	var maps = map[string]interface{}{
		"institution_name": t.InstitutionName,
	}
	institutionInfo, _ := models.GetInstitutionInfo([]string{"institution_id"}, maps)
	if institutionInfo.InstitutionID != 0 {
		return nil, errors.New("机构已存在")
	}

	// 检查用户是否已存在（事务外）
	maps = map[string]interface{}{
		"user_name": t.UserName,
	}
	userInfo, _ := models.GetUserInfo([]string{"user_id"}, maps)
	if userInfo.UserId != 0 {
		return nil, errors.New("用户已存在")
	}

	// 开启事务（仅包含修改操作）
	tx := models.GetDB().Begin()

	defer func() {
		if r := recover(); r != nil {
			tx.Rollback() // 发生 panic 时回滚事务
		}
	}()

	// 添加机构信息
	maps = map[string]interface{}{
		"institution_name": t.InstitutionName,
		"contact":          t.Contact,
	}
	InstitutionID, err := models.AddInstitutionDB(maps, tx)
	if err != nil {
		tx.Rollback() // 回滚事务
		return nil, err
	}

	// 添加用户信息
	maps = map[string]interface{}{
		"institution_id": InstitutionID,
		"user_name":      t.UserName,
		"is_master":      1,
		"user_password":  util.EncodeMD5(t.UserPassword),
	}
	_, err = models.AddUserDB(maps, tx)
	if err != nil {
		tx.Rollback() // 回滚事务
		return nil, err
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		tx.Rollback() // 提交失败时回滚
		return nil, err
	}

	return nil, nil
}

// Login 定义登录请求结构体
type EditInstitution struct {
	InstitutionID   int
	InstitutionName string
	Contact         string
	UserName        string
	UserPassword    string
}

// EditInstitution 执行用户登录逻辑
func (t *EditInstitution) EditInstitution() (map[string]interface{}, error) {
	var maps = map[string]interface{}{
		"institution_id": t.InstitutionID,
	}
	var update = map[string]interface{}{
		"institution_name": t.InstitutionName,
		"contact":          t.Contact,
	}
	err := models.EditInstitution(maps, update)
	if err != nil {
		return nil, err
	}
	maps = map[string]interface{}{
		"institution_id": t.InstitutionID,
		"is_master":      1,
	}
	update = map[string]interface{}{
		"user_password": util.EncodeMD5(t.UserPassword),
	}
	err = models.EditUser(maps, update)
	if err != nil {
		return nil, err
	}
	return nil, nil
}

// Login 定义登录请求结构体
type DeleteInstitution struct {
	InstitutionID   int
	InstitutionName string
	Contact         string
}

// DeleteInstitution 执行用户登录逻辑
func (t *DeleteInstitution) DeleteInstitution() (map[string]interface{}, error) {
	// 开启事务
	tx := models.GetDB().Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback() // 发生 panic 时回滚事务
		}
	}()

	var maps = map[string]interface{}{
		"institution_id": t.InstitutionID,
	}

	// 删除机构信息
	err := models.CleanInstitutionDB(maps, tx)
	if err != nil {
		tx.Rollback() // 回滚事务
		return nil, err
	}

	// 删除用户信息
	err = models.CleanUserDB(maps, tx)
	if err != nil {
		tx.Rollback() // 回滚事务
		return nil, err
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		tx.Rollback() // 提交失败时回滚
		return nil, err
	}

	return nil, nil
}
